package financial

import (
	"encoding/json"
	"github.com/tealeg/xlsx"
	"ltbz/cultural_tourism_api/controllers"
	"ltbz/cultural_tourism_api/models"
	"ltbz/cultural_tourism_api/models/financial"
	"ltbz/cultural_tourism_api/utils"
	"os"
	"strconv"
	"time"
)

// 合作景区
type CooperateScenicController struct {
	controllers.BaseAuthController
}

// @Title 获取合作景区统计-财务数据
// @Description 获取合作景区统计-财务数据
// @Success 200 {object} financial.CooperateScenicSpotFinancialData
// @router /cooperate_scenic_spot/financial_data [post]
func (this *ImperialPalaceController) CooperateScenicSpotFinancialData() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var condition string
	var pars []interface{}

	condition += ` AND a.trade_status='已使用' `
	condition += ` AND c.product_kind=1 `

	if this.SysUser.ScenicSpotId != "" {
		condition += ` AND b.scenic_spot_id IN (` + this.SysUser.ScenicSpotId + `)`
	}

	resp := new(financial.CooperateScenicSpotFinancialData)

	cooperateScenicSpotObj := new(financial.CooperateScenicSpot)
	//当日出票
	{
		day := time.Now().Format(utils.FormatDate)
		condition += ` AND a.create_date = ? `
		pars = append(pars, day)

		dayTotal, err := cooperateScenicSpotObj.GetCooperateScenicSpotTicket(condition, pars)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取当日出票数失败,Err:" + err.Error()
			return
		}
		resp.CurrentDayOutTicket = dayTotal
	}

	//当周出票
	{
		//获取周开始和结束日期
		weekStart := utils.GetNowWeekMonday()
		weekEnd := utils.GetNowWeekLastDay()

		condition += ` AND a.create_date >= ? `
		pars = append(pars, weekStart)

		condition += ` AND a.create_date <= ? `
		pars = append(pars, weekEnd)

		weekTotal, err := cooperateScenicSpotObj.GetCooperateScenicSpotTicket(condition, pars)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取当周出票数失败,Err:" + err.Error()
			return
		}
		resp.CurrentWeekOutTicket = weekTotal
	}

	//当月出票
	{
		now := time.Now()
		//获取月开始和结束日期
		monthStart, monthEnd := utils.GetMonthStartAndEnd(strconv.Itoa(now.Year()), strconv.Itoa(int(now.Month())))

		condition += ` AND a.create_date >= ? `
		pars = append(pars, monthStart)

		condition += ` AND a.create_date <= ? `
		pars = append(pars, monthEnd)

		monthTotal, err := cooperateScenicSpotObj.GetCooperateScenicSpotTicket(condition, pars)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取当月出票数失败,Err:" + err.Error()
			return
		}
		resp.CurrentMonthOutTicket = monthTotal
	}

	//累计出票
	{
		total, err := cooperateScenicSpotObj.GetCooperateScenicSpotTicket(condition, pars)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "获取累计出票数失败,Err:" + err.Error()
			return
		}
		resp.Total = total
	}
	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = resp
	return
}

// @Title 获取合作景区统计-订单列表
// @Description 获取合作景区统计-订单列表
// @Param	request	body financial.CooperateScenicSpotOrderListReq true "type json string"
// @Success 200 {object} financial.CooperateScenicSpotOrderListPageResp
// @router /cooperate_scenic_spot/order_list [post]
func (this *ImperialPalaceController) CooperateScenicSpotOrderList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	body := this.Ctx.Input.RequestBody
	req := new(financial.CooperateScenicSpotOrderListReq)
	if string(body) != "" {
		err := json.Unmarshal(body, &req)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}

	if req.PageSize <= 0 {
		req.PageSize = utils.PageSize20
	}
	if req.CurrentIndex <= 0 {
		req.CurrentIndex = 1
	}

	startSize := utils.StartIndex(req.CurrentIndex, req.PageSize)

	obj := new(financial.CooperateScenicSpot)

	var condition string
	var pars []interface{}

	if req.TradeCode != "" {
		condition += "AND a.trade_code = ?"
		pars = append(pars, req.TradeCode)
	}

	if req.Mobile != "" {
		mobile := `%` + req.Mobile + `%`
		condition += "AND a.mobile LIKE ?"
		pars = append(pars, mobile)
	}

	total, err := obj.GetCooperateScenicSpotOrderPageCount(condition, pars)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	list, err := obj.GetCooperateScenicSpotOrderPage(condition, pars, startSize, req.PageSize)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	page := utils.GetPaging(req.CurrentIndex, req.PageSize, total)

	resp := new(financial.CooperateScenicSpotOrderListPageResp)
	resp.Paging = page
	resp.List = list

	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = resp
	return
}

// @Title 合作景区收入-订单导出
// @Description 合作景区收入-订单导出
// @Param	request	body financial.CooperateScenicSpotOrderListExportReq true "type json string"
// @Success 200
// @router /cooperate_scenic_spot/order_list/export [get]
func (this *ImperialPalaceController) CooperateScenicSpotorderListExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	body := this.Ctx.Input.RequestBody
	req := new(financial.CooperateScenicSpotOrderListExportReq)
	if string(body) != "" {
		err := json.Unmarshal(body, &req)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}

	var condition string
	var pars []interface{}

	if req.TradeCode != "" {
		condition += "AND a.trade_code = ?"
		pars = append(pars, req.TradeCode)
	}

	if req.Mobile != "" {
		mobile := `%` + req.Mobile + `%`
		condition += "AND a.mobile LIKE ?"
		pars = append(pars, mobile)
	}

	obj := new(financial.CooperateScenicSpot)
	list, err := obj.GetCooperateScenicSpotOrderExport(condition, pars)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	style.Alignment = alignment
	style.ApplyAlignment = true
	if len(list) <= 0 {
		xlsxFile.AddSheet("暂无数据")
	}

	sheel, err := xlsxFile.AddSheet("智能桶用户")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}

	titleRow := sheel.AddRow()
	titleRow.AddCell().SetValue("序号")
	titleRow.AddCell().SetValue("景区名称")
	titleRow.AddCell().SetValue("订单编码")
	titleRow.AddCell().SetValue("用户ID")
	titleRow.AddCell().SetValue("手机号")
	titleRow.AddCell().SetValue("门票张数")
	titleRow.AddCell().SetValue("核销时间")
	for _, v := range list {
		dataRow := sheel.AddRow()
		dataRow.AddCell().SetValue(v.TradeId)
		dataRow.AddCell().SetValue("")
		dataRow.AddCell().SetValue(v.TradeCode)
		dataRow.AddCell().SetValue(v.WxUserId)
		dataRow.AddCell().SetValue(v.Mobile)
		dataRow.AddCell().SetValue(v.BuyGoodNum)
		dataRow.AddCell().SetValue(v.CreateTime)
	}
	pref := `合作景区数据_`
	savePath := `./temp/` + pref + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	err = xlsxFile.Save(savePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败,Err:" + err.Error()
		return
	}
	downloadFileName := pref + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	this.Ctx.Output.Download(savePath, downloadFileName)
	defer func() {
		os.Remove(savePath)
	}()
	br.Msg = "导出成功！"
	br.Ret = 200
}
